<?php
/**
 * zenOnFly -- provides for loading image on the fly with javascript.
 *
 * @author Antoine Gancel (titou)
 *
 * @package plugins
 */

$plugin_description = gettext("Permet d'optimiser le chargement des images");
$plugin_author = 'Antoine Gancel (titou250)';
$plugin_version = '0.2';
$plugin_URL = "https://code.google.com/p/zenonfly/wiki/ZenonflyEnglish";
$option_interface = new zenOnFlyOptions();

if (isset($_zp_gallery_page) && $_zp_gallery_page != 'index.php') {
	addPluginScript('<script src="'.WEBPATH . '/plugins/zenonfly/jquery.hotkeys-0.7.9.min.js" type="text/javascript" /></script>');
}

/**
 * Plugin option handling class
 *
 */
class zenOnFlyOptions {

	function zenOnFlyOptions() {
		/* put any setup code needed here */
		setOptionDefault('zenonfly_navButton', 'imgnav');
		setOptionDefault('zenonfly_image', 'image');
		setOptionDefault('zenonfly_title', 'title');
		setOptionDefault('zenonfly_desc', 'desc');
		setOptionDefault('zenonfly_imageId', 'imageid');
		setOptionDefault('zenonfly_imageNumber', 'imagenumber');
		setOptionDefault('zenonfly_idtag', 'idtag');
		setOptionDefault('zenonfly_comments', 'comments');
		setOptionDefault('zenonfly_customrating', 'customrating');
		setOptionDefault('zenonfly_imagemap', 'imagemap');
	}

	function getOptionsSupported() {
		return array(
			gettext('Id of navigation container') => array ('key' => 'zenonfly_navButton', 'type' => OPTION_TYPE_TEXTBOX,
						'desc' => gettext('Put here the name of navigation container ID')),
			gettext('ID of image container') => array ('key' => 'zenonfly_image', 'type' => OPTION_TYPE_TEXTBOX,
						'desc' => gettext('Put here the name of image ID container')),
			gettext('ID of title container') => array ('key' => 'zenonfly_title', 'type' => OPTION_TYPE_TEXTBOX,
						'desc' => gettext('Put here the name of title ID container')),
			gettext('ID of description container') => array ('key' => 'zenonfly_desc', 'type' => OPTION_TYPE_TEXTBOX,
						'desc' => gettext('Put here the name of description image ID container')),
			gettext('ID of imageId container') => array ('key' => 'zenonfly_imageId', 'type' => OPTION_TYPE_TEXTBOX,
						'desc' => gettext('Put here the name of Image Id ID container')),
			gettext('ID of image Number container') => array ('key' => 'zenonfly_imageNumber', 'type' => OPTION_TYPE_TEXTBOX,
						'desc' => gettext('Put here the name of ImageNumber container')),
			gettext('ID of idtag Number container') => array ('key' => 'zenonfly_idtag', 'type' => OPTION_TYPE_TEXTBOX,
						'desc' => gettext('Put here the name of Tag container')),
			gettext('ID of comments Number container') => array ('key' => 'zenonfly_comments', 'type' => OPTION_TYPE_TEXTBOX,
						'desc' => gettext('Put here the name of comment container')),
			gettext('ID of comments Rating container') => array ('key' => 'zenonfly_customrating', 'type' => OPTION_TYPE_TEXTBOX,
						'desc' => gettext('Put here the name of rating container')),
			gettext('ID of imagemap container') => array ('key' => 'zenonfly_imagemap', 'type' => OPTION_TYPE_TEXTBOX,
						'desc' => gettext('Put here the name of imagemap container')),
		);
	}

	function handleOption($option, $currentValue) {
	}
}

// FOR RATING PLUGIN, MODIFICATION du rating.php (supp de WEBPATH)

global $_zp_current_comment;
global $_zp_current_image;
global $_zp_current_album;
global $enableplugin;

// load enable plugins
foreach (getEnabledPlugins() as $key=>$value){
	$enableplugin[] = $key;
	
}

/* START ADD SPECIFIC FUNCTION FOR PLUGINS */
function addJsFlowplayer($enableplugin){
	if(in_array("flowplayer3",$enableplugin)){
		$addjs = 'function addFlowPlayer(file){';
		$addjs .= 'flv = "<span id=\'player'.$count.'\' class=\'flowplayer\' style=\'display:block; width: '.getOption('flow_player3_width').'px; height: '.getOption('flow_player3_height').'px;\'></span>;";';
		$addjs .= 'flv += "<script type=\'text/javascript\'>";';
		$addjs .= 'flv += "flowplayer(\'player'.$count.'\',\''.WEBPATH . '/' . ZENFOLDER . '/'.PLUGIN_FOLDER . '/flowplayer3/flowplayer-3.1.5.swf\', {";';
		$addjs .= 'flv += "plugins: {controls: {";';
		$addjs .= 'flv += "backgroundColor: \''.getOption('flow_player3_controlsbackgroundcolor').'\',";';
		$addjs .= 'flv += "backgroundGradient: \''.getOption('flow_player3_controlsbackgroundcolorgradient').'\',";';
		$addjs .= 'flv += "autoHide: \''.getOption('flow_player3_controlsautohide').'\',";';
		$addjs .= 'flv += "timeColor:\''.getOption('flow_player3_controlstimecolor').'\',";';
		$addjs .= 'flv += "durationColor: \''.getOption('flow_player3_controlsdurationcolor').'\',";';
		$addjs .= 'flv += "progressColor: \''.getOption('flow_player3_controlsprogresscolor').'\',";';
		$addjs .= 'flv += "progressGradient: \''.getOption('flow_player3_controlsprogressgradient').'\',";';
		$addjs .= 'flv += "bufferColor: \''.getOption('flow_player3_controlsbuffercolor').'\',";';
		$addjs .= 'flv += "bufferGradient: \''.getOption('flow_player3_controlsbuffergradient').'\',";';
		$addjs .= 'flv += "sliderColor: \''.getOption('flow_player3_controlsslidercolor').'\',";';
		$addjs .= 'flv += "sliderGradient: \''.getOption('flow_player3_controlsslidergradient').'\',";';
		$addjs .= 'flv += "buttonColor: \''.getOption('flow_player3_controlsbuttoncolor').'\',";';
		$addjs .= 'flv += "buttonOverColor: \''.getOption('flow_player3_controlsbuttonovercolor').'\',";';
		$addjs .= 'flv += "scaling: \''.getOption('flow_player3_scaling').'\'}},";';
		$addjs .= 'flv += "canvas: {backgroundColor: \''.getOption('flow_player3_backgroundcolor').'\',";';
		$addjs .= 'flv += "backgroundGradient: \''.getOption('flow_player3_backgroundcolorgradient').'\'},";';
		$addjs .= 'flv += "clip:{url:\'"+file+"\',autoPlay: false '.$autoplay.',autoBuffering: true,scaling: \''.getOption('flow_player3_scaling').'\'}";';
		$addjs .= 'flv += "})<\/script>";';
		$addjs .= 'return flv;';
		$addjs .= '}';
		return $addjs;
	}
}

// add specific function for Class-object plug in
function addClassObject($enableplugin){
	if(in_array("class-textobject",$enableplugin)){
		$addClassObject =  'function addTextObject(file){';
		$addClassObject .= 'textObject = $.ajax({url:file,dataType:"html",async: false});';
		$addClassObject .= 'return textObject.responseText;';
		$addClassObject .= '}';
		return $addClassObject;
	}
}

// If comment plugin is loaded, gets comments posted
function getComment(){
	$addComment = '<h3>'.addslashes(gettext("Comments")).'('.addslashes(getCommentCount()).')</h3><hr />';
	// Browse all comment of an image and build html for comments
	while (next_comment()){
		$comment = str_replace(CHR(10),"",getCommentBody()); 
		$comment = str_replace(CHR(13),"",$comment); 
		if(getCommentAuthorSite)
			$link = '<a href=\"'.addslashes(getCommentAuthorSite()).'\" title=\"Go to Author link\">'.addslashes(getCommentAuthorName()).'</a>';
		else
			$link = "";
		$addComment .= '<div class=\"comment\"><div class=\"commentmeta\"><span class=\"commentauthor\">'.$link.'</span></div>';
		$addComment .= '<div class=\"commentbody\">'.addslashes($comment).'</div>';
		$addComment .= '<div class=\"commentdate\" id=\"commentdate\">'.addslashes(getCommentDateTime()).',';
		$addComment .= "</div></div>";
	}
	return $addComment;
}

function getTag(){
	$singletag = getTags();
	$tagstring = implode(', ', $singletag);
 	if ($tagstring === '' or $tagstring === NULL ) {
		$preText = '';
		if ( $messageIfEmpty === true && $editable && zp_loggedin() ) {
			$tagstring = gettext('(No tags...)');
		} elseif ( is_string($messageIfEmpty) ) {
			$tagstring = $messageIfEmpty;
		}
	}
	$listTag ='';
	if (count($singletag) > 0) {
		if (!empty($preText)) {
			$listTag .=  '<span class="tags_title">'.$preText.'</span>';
		}
		$listTag.= '<ul class="'.$class.'">';
		if (is_object($_zp_current_search)) {
			$albumlist = $_zp_current_search->album_list;
		} else {
			$albumlist = NULL;
		}
		$ct = count($singletag);
		$x = 0;
		foreach ($singletag as $atag) {
			if ($x++ == $ct) { $separator = ""; }
			if ($option === "links") {
				$links1 = '<a href="'.htmlspecialchars(getSearchURL($atag, '', 'tags', 0, 0, $albumlist)).'\' title="'.html_encode($atag).'\' rel="nofollow">';
				$links2 = '</a>';
			}
			$listTag .= '<li>'.$links1.$atag.$links2.$separator.'</li>';
		}
		$listTag .= '</ul>';
	} else {
		$listTag .= "$tagstring";
	}
	return addslashes($listTag);
}

// specific function to load google map...using phoogle but not google_maps.php
function printCustomImageMap(){
	global $_zp_themeroot;
	global $_zp_phoogle;
	
	if($zoomlevel){$_zp_phoogle->zoomLevel = $zoomlevel;}
	if (!is_null($width)) {$_zp_phoogle->setWidth($width);} else {$_zp_phoogle->setWidth(getOption('gmaps_width'));}
	if (!is_null($height)) {$_zp_phoogle->setHeight($height);} else {$_zp_phoogle->setHeight(getOption('gmaps_height'));}
	if (!is_null($mapcontrol)) {$_zp_phoogle->setControlMap($mapcontrol);} else {$_zp_phoogle->setControlMap(getOption('gmaps_control'));}
	if (!is_null($maptypecontrol)) {$_zp_phoogle->setControlMapType($maptypecontrol);} else {$_zp_phoogle->setControlMapType(getOption('gmaps_control_maptype'));}
	if (!is_null($background)) {$_zp_phoogle->setBackGround($background);} else {$_zp_phoogle->setBackGround(getOption('gmaps_background'));}
	if (!is_null($customJS)) {$_zp_phoogle->customJS=$customJS;}
		
	 echo 'function showmap(latitude, longitude, latref, longref, desc, title){
		if($("#legendimagemap").size()==0) {
			$("#'.getOption('zenonfly_imagemap').'").before("<div id=\"legendimagemap\">'.gettext('Google Map').'</div>");
			$("#legendimagemap").click(function(){$("#'.getOption('zenonfly_imagemap').'").toggle("slow");});
		}
		if (latitude=="" && longitude==""){
			$("#legendimagemap").remove();
			$("#'.getOption('zenonfly_imagemap').'").hide();
		}
		else {$("#'.getOption('zenonfly_imagemap').'").show("slow");}
		if(latref=="S"){latitude="-"+latitude;}else{latitude = latitude;}
		if(longref=="W"){longitude="-"+longitude;}else {longitude=longitude;}
		if(desc==""){desc = title;}
			
	   	if (GBrowserIsCompatible()) {
			//if(typeof(map)==\'undefined\'){
				map = new GMap2(document.getElementById("'.getOption('zenonfly_imagemap').'"), {size:new GSize('.getOption('gmaps_width').','.getOption('gmaps_height').'),backgroundColor:\''.$_zp_phoogle->backGround.'\'});
				map.enableScrollWheelZoom();';
				$types = explode('; ', $_zp_phoogle->mapselections); 
				foreach ($types as $control) {
					if (!empty($control)) {
						echo $control.";";
					}
				}
				echo $_zp_phoogle->mapTypeControl;
				echo $_zp_phoogle->controlType;
				echo $_zp_phoogle->defaultMap;
				if ($autozoom) {
					echo '
					var latlngbounds = new GLatLngBounds( );
					for ( var i = 0; i < latlng.length; i++ ) {
						latlngbounds.extend( latlng[ i ] );
					}
					map.setCenter( latlngbounds.getCenter( ), map.getBoundsZoomLevel( latlngbounds ) );';
				}
				echo $_zp_phoogle->customJS;
				echo '
				map.setCenter(new GLatLng(latitude,longitude),'.$_zp_phoogle->zoomLevel.');
			//}
			latlng = new GLatLng(latitude,longitude);
			map.panTo(latlng);
			var pointHtml = desc;
			map.addOverlay(createMarker(latlng, pointHtml));
		} else {
			var text = document.createTextNode("'.gettext('Your browser is not compatible with Google maps').'");
			document.getElementById("'.getOption('zenonfly_imagemap').'").appendChild(text);
		}
	}';
}
/* END ADD SPECIFIC FUNCTION FOR PLUGINS */

/* BROWSE ALL IMAGE OF SELECTED ALBUM */
function browsealbum($enableplugin){
	global $_zp_current_image;
	$images = array();
	$i=0;
	while (next_image(true)){
		//Check if next_image is a valid photo or video . If not, we use classic navigation.
		if (isImagePhoto($_zp_current_image))
			$images[$i]["type"] = 1;	// 1 = photo
		else if(isImageVideo($_zp_current_image)){
			$images[$i]["type"] = 2; // 2 = video
		}
		else {
			$images[$i]["type"] = 3;	 // 3 != (photo or video)
			$txtcontent = true;
		}
		// add ImageID
		$images[$i]["id"] = getImageId();
		// add src
		if ($images[$i]["type"]==1){
			$images[$i]["src"] = getDefaultSizedImage();
		}
		else {
			$images[$i]["src"] = getUnprotectedImageURL();
		}
		// add title
		$images[$i]["title"] = addslashes(getImageTitle());
		// add filename
		$images[$i]["file"] = $_zp_current_image->getFileName();
		// add description
		$images[$i]["desc"] = addslashes(getImageDesc());
		// add comments
		if(function_exists('printCommentForm')) {$images[$i]["comments"]= getComment();}
		// add tags
		$images[$i]["tags"]= getTag($enableplugin);
		// add latitude
		$exif = getImageMetaData();
		$images[$i]["lat"]= $exif['EXIFGPSLatitude'];
		$images[$i]["latRef"] = $exif['EXIFGPSLatitudeRef'];
		//add longitude
		$images[$i]["long"]= $exif['EXIFGPSLongitude'];
		$images[$i]["longRef"] = $exif['EXIFGPSLongitudeRef'];
		//add rating
		if(function_exists('printRating')){
			$images[$i]["rating"]= round(getRating()*(getOption('rating_split_stars')+1));
		}
		$i++;
	}
	return $images;
}

function printZenOnFly(){
global $enableplugin;
?>
<script type="text/javascript">
	var images = new Array();
	var affich = new Array();
	var current = <?php global $_zp_current_image; echo $_zp_current_image->getIndex(); ?>;
	var nextimg ;

	
jQuery().ready(function(){
	var comments;
	// Create new navigation button for zenonfly
	$("#<?php echo getOption('zenonfly_navButton') ?>").html("<div class='imgprevious'>&laquo; <?php echo gettext("prev"); ?></div><div class='imgnext'><?php echo gettext("next"); ?> &raquo;</span></div>");
	<?php
	$images = browsealbum($enableplugin);
	// create table wich contains all photo in javascript
	for ($i=0; $i<count($images); $i++){
		if(function_exists('printCommentForm'))
			echo 'comments = "'.$images[$i]["comments"].'";';
		echo "\n";
		echo "images.push(new Array(".$images[$i]["type"].",".$images[$i]["id"].",'".$images[$i]["src"]."','".$images[$i]["title"]."','".$images[$i]["desc"]."',comments,'".$images[$i]["tags"]."','".$images[$i]["lat"]."','".$images[$i]["long"]."','".$images[$i]["latRef"]."','".$images[$i]["longRef"]."','".$images[$i]["file"]."','".$images[$i]["rating"]."'));";
		echo "\n";
	}
	// If plugins map is present, replace map container
	if(function_exists('printImageMap')){
		echo 'showmap(images[current][7],images[current][8],images[current][9],images[current][10],images[current][4],images[current][3]);';
	}
	?>
	
	// Define next image for
	var next = current+1;
	if (next >= images.length)
		next = 0;
	// Define previous image
	var prev = current - 1;
	if (prev <0)
		prev = images.length-1
	// preload prev and next image
	$.preloadImages(images[next][0],images[next][2],'next',images[next][3],images[next][4],images[next][7],images[next][8],images[next][9],images[next][10]);
	$.preloadImages(images[prev][0],images[prev][2],'prev',images[prev][3],images[prev][4],images[prev][7],images[prev][8],images[prev][9],images[prev][10]);

	// Add navigation with hot keys (using plugin jquery on folder js)
	$(document).bind('keydown', 'right', jQuery.nextImage);
	$(document).bind('keydown', 'left', jQuery.prevImage);
	
	// Add action to the click (like "onclick")
	$(".imgprevious").click(function(){
		$.prevImage();
	});
	// Add action to the click (like "onclick")
	$(".imgnext").click(function(){
		$.nextImage();
	});
});

//Function  which preload image (or FLV). If it's FLV, we need to build HTML...
jQuery.preloadImages = function()
{
	var flv;
	// Check if the extension is "flv"
    if(arguments[0]==2)
		flv = addFlowPlayer(arguments[1]);
	else if (arguments[0]==3)
		flv = addTextObject(arguments[1]);
	else
		flv = $("<img>").attr("src", arguments[1]);	
	// Define the variable "nextimg" or "previmg" with the dom created	
	if (arguments[2]=="next"){
    	nextimg = flv;
	}
	else {
		previmg = flv;
	}
}

//function to load next image
jQuery.nextImage = function()
{
	var next = current + 1;
	if (next >= images.length){next = 0;}  /*wrap around*/
	switchImages(next,current,1);
	current = next;
}
//function to load previous image
jQuery.prevImage = function()
{
	var prev = current - 1;
	if (prev <0){prev = images.length-1;}  /*wrap around*/
	switchImages(prev,current,0);
	current=prev;
}
// the most important: this function is use to switch image, comment, title; description ..... 
function switchImages(index,old,type) {
	// replace image container
	if (type==1)
		$("#<?php echo getOption('zenonfly_image') ?>").html(nextimg);
	else
		$("#<?php echo getOption('zenonfly_image') ?>").html(previmg);
	// replace title container
	$("#<?php echo getOption('zenonfly_title') ?>").html(images[index][3]);
	// replace description container
	$("#<?php echo getOption('zenonfly_desc') ?>").html(images[index][4]);
	// replace imageid container (for comment form)
	$("#<?php echo getOption('zenonfly_imageid') ?>").val(images[index][1]);
	// replace imagenumber container (for comment form)
	$("#<?php echo getOption('zenonfly_imagenumber') ?>").text(index+1);
	// replace idtag container
	$("#<?php echo getOption('zenonfly_idtag') ?>").html(images[index][6]);
	<?php
	// If plugins content is present, replace comments container (for comment load new comment)
	if(function_exists('printCommentForm')){
		echo '$("#'.getOption('zenonfly_comments').'").html(images[index][5]);';
		echo '$("textarea[@name=\'comment\']").val("");';
	}

	// If plugins map is present, replace map container
	if(function_exists('printImageMap')){
		echo 'showmap(images[index][7],images[index][8],images[index][9],images[index][10],images[index][4],images[index][3]);';
	}
	if (function_exists('printImageRating')){
	?>
		toto = $.ajax({url:'<?php echo FULLWEBPATH;?>/plugins/zenonfly/ajax.php',
		data:({op:2,filename:images[index][11],albumname : "<?php echo $_zp_current_image->getAlbumName();?>"}),
		async : false}).responseText;
		$("#<?php echo getOption('zenonfly_customrating') ?>").replaceWith("<div id='<?php echo getOption('zenonfly_customrating') ?>'>"+toto+"</div>");
		$('input[type=radio].star').rating();
		$('#star_rating_images_'+images[index][1]+' :radio.star').rating('select',images[index][12]);
	<?php
	}
	?>
	// add filename to url (for the future "historisation" => no specific action for the moment
	document.location.replace('#'+images[index][11]);

	// Define next image
	next = index+1;
	if (index+1 >= images.length)
		next = 0;
	prev = index-1;
	// Define previous image
	if (prev<0)
		prev = images.length-1;
	// preload prev and next image
	$.preloadImages(images[next][0],images[next][2],'next',images[next][3],images[next][4],images[next][7],images[next][8],images[next][9],images[next][10]);
	$.preloadImages(images[prev][0],images[prev][2],'prev',images[prev][3],images[prev][4],images[prev][7],images[prev][8],images[prev][9],images[prev][10]);

	// load hitcounter function for new image loaded
	<?php if (!isMyALbum($album->name, ALL_RIGHTS)) { ?>
	$.get("<?php echo FULLWEBPATH; ?>/plugins/zenonfly/ajax.php?op=1&album=<?php echo pathurlencode($_zp_current_album->name); ?>&img="+images[index][11]);
	<?php } ?>

	<?php
	// if we are in admin mode, we delete admin option of deleting or edit an image (It's too hard to change for the moment).
	if (function_exists('printAdminToolbox')){
		echo '$("#admin_data > ul > li > a[title=\''.addslashes(gettext("Delete image")).'\']").remove();
		$("#admin_data > ul > li > a[title=\''.addslashes(gettext("Edit this image")).'\']").remove();
		';
	}
	?>

}

<?php echo addJsFlowplayer($enableplugin);?>

<?php echo addClassObject($enableplugin);?>

<?php if(function_exists('printImageMap')){echo printCustomImageMap();}?>

	</script>
<?php
}
?>